import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: false, // 跨域请求时发送cookie
  timeout: 60000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    console.log('----------------request---------------error:')
    console.log(error)
    if (error.response.status === 504 || error.response.status === 404) {
      this.$message.error('服务器被吃了⊙﹏⊙∥')
    } else if (error.response.status === 403) {
      this.$message.error('权限不足,请联系管理员⊙﹏⊙∥')
    } else {
      this.$message.error('未知错误!')
    }
    console.log(error, '-------------->') // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        message: res.msg || 'error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
      // to re-login
        MessageBox.confirm('您已退出，可以取消此页面，或者重新登录', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(res.msg || 'error2')
    } else {
      return res
    }
  },
  error => {
    console.log('----------------response---------------error:')
    console.log(error)
    console.log(error.response)
    const { config, code, message } = error
    console.log(config, code, message)
    // 如果发生错误 重新尝试
    if (!error.response) {
      const config = error.config
      console.log('config-->', config)
      // If config does not exist or the retry option is not set, reject
      if (!config || !config.retry) return Promise.reject(error)

      // Set the variable for keeping track of the retry count
      config.__retryCount = config.__retryCount || 0

      // Check if we've maxed out the total number of retries
      if (config.__retryCount >= config.retry) {
        // Reject with the error
        return Promise.reject(error)
      }

      // 增加重试次数
      config.__retryCount += 1

      // 创建新的Promise来处理指数退避
      const backoff = new Promise(function(resolve) {
        setTimeout(function() {
          resolve()
        }, config.retryDelay || 1)
      })

      // 返回Promise，在该Promise中召回axios重试请求
      return backoff.then(function() {
        return axios(config)
      })
    }
    if (error.response.status === 504 || error.response.status === 404) {
      Message({
        message: '服务器被吃了⊙﹏⊙∥',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.response.status === 403) {
      Message({
        message: '权限不足，请联系管理员⊙﹏⊙∥',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.response.status === 500) {
      Message({
        message: '服务器报错啦⊙﹏⊙∥',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.response.status === 506) {
      Message({
        message: '登录信息失效，请刷新页面',
        type: 'error',
        duration: 5 * 1000
      })
      window.location.reload()
    } else {
      Message({
        message: '未知错误⊙﹏⊙∥',
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  })

// response interceptor
/*
service.interceptors.response.use(

 */
/**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

/**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
/*
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        message: res.msg || 'error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('您已退出，可以取消此页面，或者重新登录', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(res.msg || 'error2')
    } else {
      return res
    }
  },
  error => {
    console.log('----------------response---------------error:')
    console.log(error)
    if (error.response.status === 504 || error.response.status === 404) {
      Message({
        message: '服务器被吃了⊙﹏⊙∥',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.response.status === 403) {
      Message({
        message: '权限不足，请联系管理员⊙﹏⊙∥',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.response.status === 500) {
      Message({
        message: '服务器报错啦⊙﹏⊙∥',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.response.status === 506) {
      Message({
        message: '登录信息失效，请刷新页面',
        type: 'error',
        duration: 5 * 1000
      })
      window.location.reload()
    } else {
      Message({
        message: '未知错误⊙﹏⊙∥',
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)
*/
export default service
